package com.huike.controller;

import com.huike.po.Friend;
import com.huike.po.User;
import com.huike.po.UserDetail;
import com.huike.po.UserOnline;
import com.huike.pojo.LoginForm;
import com.huike.pojo.RegisterForm;
import com.huike.pojo.Response;
import com.huike.service.FriendService;
import com.huike.service.FriendServiceImpl;
import com.huike.service.UserService;
import com.huike.websocket.ChatWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    public UserService userService;
    @Autowired
    public FriendService friendService;
    @Autowired
    public Response response;

    @RequestMapping(value = "/login" ,method=RequestMethod.POST)
    @ResponseBody
    public Response login(@RequestBody LoginForm loginUser, HttpSession session) {
        if (null != session.getAttribute("loginUser")) {
            session.removeAttribute("loginUser");
        }
        // 根据表单信息匹配用户
        User user = userService.login(loginUser);
        if (user!=null) {
            // 存储到会话中
            session.setAttribute("loginUser", user);
            response.setCode("200");
            response.setContent(userService.getLoginCallBack(user));
        } else{
            response.setCode("404");
            response.setContent("");
        }
        return response;
    }

    @RequestMapping(value = "/logout" ,method=RequestMethod.POST)
    @ResponseBody
    /**
     * 用户下线后，给所有订阅该用户在线状态的账号，发送下线提醒
     */
    public Response logout(@RequestBody UserOnline userOnline, HttpSession session) {
          response.setCode("200");
          response.setContent("");
        return response;
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public Response register(@RequestBody RegisterForm registerForm, HttpSession session) {
        boolean res = userService.register(registerForm);
        if(res) {
            response.setCode("200");
            response.setContent("");
        } else {
            response.setCode("400");
            response.setContent("");
        }
        return response;
    }

    @RequestMapping(value = "/searchUser")
    @ResponseBody
    public Response searchUser(String account, HttpSession session) {
        UserDetail searchUser = userService.searchUserByAccount(account);
        if (searchUser!= null) {
            response.setCode("200");
            response.setContent(searchUser);
        } else {
            response.setCode("404");
            response.setContent("");
        }
        return response;
    }
}
